package com.lsh.payment.core.strategy.payment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.payment.core.constant.BusinessConstant;
import com.lsh.payment.core.exception.BusinessException;
import com.lsh.payment.core.model.payenum.PayChannel;
import com.lsh.payment.core.strategy.config.MisPayConfig;
import com.lsh.payment.core.strategy.config.XYPayConfig;
import com.lsh.payment.core.strategy.vo.mispurse.MisPurseResponse;
import com.lsh.payment.core.util.HttpClientUtils;
import com.lsh.payment.core.util.pay.wxpay.WxSignature;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Project Name: lsh-payment
 *
 * @author peter
 * @date 16/11/23
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Component
@Lazy(value = false)
public class MisPursePayStrategy implements PayStrategy<MisPurseResponse>, InitializingBean {

    private static final String PAYMENT_API = "/trade/info/pay";

    private Logger logger = LoggerFactory.getLogger(MisPursePayStrategy.class);

    /**
     * 调用对应支付平台组装支付请求报文
     *
     * @param payType  传入需要的支付方式
     * @param paramMap 其他额外需要的参数
     * @return 生成的支付请求
     */
    @Override
    public MisPurseResponse generatePayParams(int payType, final Map<String, String> paramMap) {
        logger.info("请求mis下单: " + paramMap);
        BigDecimal amount = new BigDecimal(paramMap.get("payAmount"));
        String payPaymentNo = paramMap.get("payPaymentNo");
        String channelType = paramMap.get("channelType");
        String uid = paramMap.get("uid");
        String payMethod;
        boolean is_balance = false;
        if (channelType.equals(PayChannel.PURSE_ON_CREDIT_PAY.getCode() + "")) {
            payMethod = "3";
        } else if(channelType.equals(PayChannel.PURSE_PRE_PAY.getCode() + "")) {
            payMethod = "4";
        }else if(channelType.equals(PayChannel.PURSE_BALANCE_PAY.getCode() + "")) {
            payMethod = "2";
            is_balance = true;
        }else {
            return null;
        }

        Map<String, Object> mispayRequestBody = new HashMap<>(12);

        mispayRequestBody.put("appid", MisPayConfig.APPID);
        mispayRequestBody.put("uid", uid);
        // 3 订单支付
        mispayRequestBody.put("is_balance", is_balance + "");
        mispayRequestBody.put("from_type", "3");
        mispayRequestBody.put("pay_method", payMethod);
        mispayRequestBody.put("out_trade_no", payPaymentNo);
        mispayRequestBody.put("money", amount.toString());
        mispayRequestBody.put("notify_url", XYPayConfig.NOTIFY_URL);

        int timestamp = (int) (System.currentTimeMillis() / 1000);

        String sign = WxSignature.getMisSign(mispayRequestBody, MisPayConfig.APPID, timestamp);
        Map<String, String> headMap = new HashMap<>();

        headMap.put("timestamp", timestamp + "");
        headMap.put("accesskey", MisPayConfig.APPID);
        headMap.put("sign", sign);
        logger.info("mis下单参数 {}", JSON.toJSONString(mispayRequestBody));

        String misResultStr = HttpClientUtils.doPost(MisPayConfig.PAY_API + PAYMENT_API, mispayRequestBody, headMap);
        //构造返回报文
        logger.info(payPaymentNo + "-misResult is " + misResultStr);

        return this.buildRsp(misResultStr, payPaymentNo);
    }


//    public static void main(String[] args) {
//
//        Map<String, Object> mispayRequestBody = new HashMap<>(12);
//
//        mispayRequestBody.put("appid", 1000);
//        mispayRequestBody.put("uid", "323224242424");
//        // 3 订单支付
//        mispayRequestBody.put("is_balance", true + "");
//        mispayRequestBody.put("from_type", "3");
//        mispayRequestBody.put("pay_method", 2);
//        mispayRequestBody.put("out_trade_no", "32393918918291");
//        mispayRequestBody.put("money", "23.00");
//
//        Map<String, String> headMap = new HashMap<>();
//        int timestamp = (int) (System.currentTimeMillis() / 1000);
//        headMap.put("timestamp", timestamp + "");
//        headMap.put("accesskey", "1000");
//        headMap.put("sign", "jashiadbiuwqhfenfn");
//
//        String misResultStr = HttpClientUtils.doPost("http://dev.market-wallet.wmdev2.lsh123.com" + PAYMENT_API, mispayRequestBody, headMap);
//        //构造返回报文
//        System.out.println("-misResult is " + misResultStr);
//    }
    /**
     * 钱方支付查询返回值
     *
     * @param misResultStr 返回结果
     * @param payPaymentNo 请求钱数
     * @return 支付平台返回结果
     */
    private MisPurseResponse buildRsp(String misResultStr, String payPaymentNo) {

        MisPurseResponse response = new MisPurseResponse();
        response.setCode(BusinessConstant.PAY_REQUEST_FAIL);
        response.setMsg(BusinessConstant.PAY_REQUEST_FAIL_MESSAGE);

        if (StringUtils.isBlank(misResultStr)) {
            return response;
        }

        JSONObject misResult = JSON.parseObject(misResultStr);
        String ret = misResult.getString("ret");
        if (StringUtils.isBlank(ret) || !ret.equals("0")) {
            response.setMsg(misResult.getString("msg"));
            return response;
        }

        JSONObject content = misResult.getJSONObject("content");
        if(content.isEmpty()){
            response.setMsg(misResult.getString("msg"));

            return response;
        }
        String tradeId = content.getString("trade_id");

        if (StringUtils.isBlank(tradeId)) {
            response.setMsg(misResult.getString("msg"));

            return response;
        }

        response.setCode(BusinessConstant.PAY_REQUEST_SUCCESS);
        response.setMsg("success");
        response.setTransactionId(tradeId);
        response.setTrade_money(content.getString("trade_money"));
        response.setStatus(content.getString("status"));
        response.setOut_trade_no(content.getString("out_trade_no"));
        response.setTrade_id(tradeId);
        response.setPay_change_money(content.getString("pay_change_money"));

        return response;
    }

    @Override
    public void afterPropertiesSet() throws BusinessException {
        PayStrategyFactory.register(BusinessConstant.MIS_PAY, this);
    }
}
